<?php
/*
 * Copyright 2009 Eat Local Food, LLC
 * Copyright (c) 2007 osCommerce (this file was written after
 * code review of osCommerce).
 *
 * This file is part of gwtCommerce.
 *
 * gwtCommerce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * gwtCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gwtCommerce.  If not, see <http://www.gnu.org/licenses/>.
 */

define('IN_ADMIN_COMPONENT_CONTROLLER', 'true');

class WhosOnlineComponent
{
	function WhosOnlineComponent()
	{
	}

	function action(&$params, $action)
	{
		return $this->query($params);
	}

	function query(&$params) 
	{
		$handle = get_class($this);
		$paginate = (boolean)$params['paginate'];
		$max_rows = (int)$params['max_rows'];
		$offset = (int)$params['offset'];

		$current_time = time();
		$xx_mins_ago = ($current_time - 900);

		$sql = "delete from " . TABLE_WHOS_ONLINE . " where time_last_click < '" . $xx_mins_ago . "'";
		mysql_query($sql) or die(mysql_error());

		$sqlQuery = 'select who.full_name, who.ip_address, who.time_entry, who.time_last_click, who.last_page_url ' .
		'from ' . TABLE_WHOS_ONLINE . ' who order by who.time_last_click DESC';
		if ($paginate) {
			$sqlQuery .= ' limit ' . $offset . ', ' . $max_rows;
		}
		$dataReturned = mysql_query($sqlQuery) or die(mysql_error());
		$i = 0;
		while($row = mysql_fetch_array($dataReturned))
		{
			$value{$handle}{$i}{'full_name'}= $row['full_name'];
			$value{$handle}{$i}{'ip_address'}= $row['ip_address'];
			$time_entry = (int)$row['time_entry'];
			$value{$handle}{$i}{'time_entry'} = strftime("%Y-%m-%d %H:%M:%S", $time_entry);
			$time_last_click = (int)$row['time_last_click'];
			$value{$handle}{$i}{'time_last_click'} = strftime("%Y-%m-%d %H:%M:%S", $time_last_click);
			$value{$handle}{$i}{'last_page_url'}= $row['last_page_url'];
			$i++;
		}

		if ($paginate) {
			$sqlQuery = 'select count(full_name) as cnt from ' . TABLE_WHOS_ONLINE;
			$dataReturned = mysql_query($sqlQuery) or die(mysql_error());
			$cnt = 0;
			while($row = mysql_fetch_array($dataReturned))
			{
				$cnt = (int)$row['cnt'];
			}

			$value{$handle . 'MetaData'}{'max_rows'}= (int)$max_rows;
			$value{$handle . 'MetaData'}{'offset'}= $offset;
			$value{$handle . 'MetaData'}{'page_links_max'} = (int)MAX_DISPLAY_PAGE_LINKS;
			$value{$handle . 'MetaData'}{'rows'}= $i;
			$value{$handle . 'MetaData'}{'total_rows'}= $cnt;
		}

		return $value;
	}
}
?>
